package com.wedding.app.service.impl;

import com.wedding.app.entity.User;
import com.wedding.app.mapper.UserMapper;
import com.wedding.app.service.EmailService;
import com.wedding.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

// 用于存储验证码，实际项目中应该使用Redis
class CodeInfo {
    private String code;
    private long expireTime;

    public CodeInfo(String code, long expireTime) {
        this.code = code;
        this.expireTime = expireTime;
    }

    public String getCode() {
        return code;
    }

    public boolean isExpired() {
        return System.currentTimeMillis() > expireTime;
    }
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailService emailService;

    @Value("${mail.code-expire-minutes}")
    private int codeExpireMinutes;

    // 用于存储验证码，实际项目中应该使用Redis
    private static Map<String, CodeInfo> codeMap = new HashMap<>();

    @Override
    public User selectById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User selectByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public int insert(User user) {
        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setStatus(0); // 默认正常状态
        return userMapper.insert(user);
    }

    @Override
    public int update(User user) {
        // 如果密码不为空，则加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        return userMapper.update(user);
    }

    @Override
    public int deleteById(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        return userMapper.updateStatus(id, status);
    }

    @Override
    public int updatePassword(Long id, String password) {
        // 密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userMapper.updatePassword(id, password);
    }

    @Override
    public User login(String username, String password) {
        // 密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = userMapper.selectByUsername(username);
        if (user != null && user.getPassword().equals(password) && user.getStatus() == 0) {
            return user;
        }
        return null;
    }

    @Override
    public User loginByEmail(String email, String code) {
        // 验证验证码
        if (verifyCode(email, code)) {
            User user = userMapper.selectByUsername(email); // 假设username字段存储邮箱
            if (user != null && user.getStatus() == 0) {
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean sendCode(String email) {
        // 生成6位验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        // 存储验证码并设置过期时间
        long expireTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(codeExpireMinutes);
        codeMap.put(email, new CodeInfo(code, expireTime));
        
        // 获取用户名（实际项目中可能需要根据邮箱查询用户信息）
        // 这里假设用户在注册时先输入邮箱和用户名，再获取验证码
        String username = "用户";
        User user = userMapper.selectByUsername(email); // 假设username字段存储邮箱
        if (user != null) {
            username = user.getUsername();
        }
        
        // 调用邮件服务发送验证码
        boolean result = emailService.sendCodeEmail(email, code, username);
        
        if (result) {
            System.out.println("邮件发送成功，验证码: " + code);
        } else {
            System.out.println("邮件发送失败");
        }
        
        return result;
    }

    @Override
    public boolean verifyCode(String email, String code) {
        CodeInfo codeInfo = codeMap.get(email);
        if (codeInfo == null) {
            return false;
        }
        
        // 检查验证码是否过期
        if (codeInfo.isExpired()) {
            codeMap.remove(email);
            return false;
        }
        
        // 检查验证码是否匹配
        boolean matched = code != null && code.equals(codeInfo.getCode());
        
        // 验证成功后移除验证码（可选，防止重复使用）
        if (matched) {
            codeMap.remove(email);
        }
        
        return matched;
    }
}